/**
 * (created at 2010-12-27)
 */
package qiushuo.mysqlparser.recognizer;

import qiushuo.mysqlparser.util.HashCodeBuilder;
import qiushuo.mysqlparser.util.ObjectUtil;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class SQLToken {
    /** start from 0 */
    private final int pos;
    /** normalized text */
    private final String text;
    private final SQLTokenType type;
    /** size of original text */
    private final int orgSize;

    public SQLToken(String text, int pos, int orgSize, SQLTokenType type) {
        this.pos = pos;
        this.text = text;
        this.type = type;
        this.orgSize = orgSize;
    }

    @Override
    public int hashCode() {
        HashCodeBuilder builder = new HashCodeBuilder();
        builder.append(text).append(type);
        return builder.toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) return true;
        if (!(obj instanceof SQLToken)) return false;
        SQLToken that = (SQLToken) obj;
        return ObjectUtil.equals(that.text, this.text) && ObjectUtil.equals(that.type, this.type);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("token{")
          .append(type)
          .append(", ")
          .append(pos)
          .append(", ")
          .append(orgSize)
          .append(", ")
          .append(text)
          .append("}");
        return sb.toString();
    }

    public boolean isTypeOf(SQLTokenType type) {
        return this.type.equals(type);
    }

    public int getOrgSize() {
        return orgSize;
    }

    public int getPos() {
        return pos;
    }

    // QS_TODO distinct `id1` with id1; 'abc' and _latin1'abc'

    /**
     * @return merged raw format. e.g. for <code>id1 . `id2`</code>, return
     *         <code>id1.`id2`</code>; for <code>_latin1'abc' "d'ef" </code>,
     *         return <code>_latin1'abcd\'ef'</code>
     */
    public String getText() {
        return text;
    }

    public SQLTokenType getType() {
        return type;
    }
}
